package host

import (
	"fmt"

	"github.com/apache/iotdb-client-go/client"
	"github.com/nick/vdamtools/apps/dashboard/cmd"
	"github.com/nick/vdamtools/apps/monitor"
	"github.com/nick/vdamtools/pkg/iotdb"
	"github.com/nick/vdamtools/pkg/loggerv"
	"go.uber.org/zap"
)

func handleServerData(data monitor.ServerData) {
	//查看 data.Hostname   root.vms.vm_[Hostname] 如果不存在则创建
	ins := iotdb.GetInstance()
	dbName := fmt.Sprintf("root.vms.vm_%v", data.Hostname)
	if monitor.Hosts.AddHostInfoIfNotExists(dbName, data) { //不存在则返回TRUE，初始化数据库和时间序列
		if !ins.IsDbExist(dbName) {
			loggerv.Logger.Info("host not exist", zap.Any("dbName:", dbName))
			ins.SetStorageGroup(dbName)
		}
		initTimeSeries(ins, fmt.Sprintf("%s.hostname", dbName), client.TEXT, client.PLAIN, client.SNAPPY)
		initTimeSeries(ins, fmt.Sprintf("%s.event_time", dbName), client.INT64, client.PLAIN, client.SNAPPY)
		initTimeSeries(ins, fmt.Sprintf("%s.total_cpu_usage", dbName), client.DOUBLE, client.PLAIN, client.SNAPPY)
		initTimeSeries(ins, fmt.Sprintf("%s.mem_total", dbName), client.INT64, client.PLAIN, client.SNAPPY)
		initTimeSeries(ins, fmt.Sprintf("%s.mem_available", dbName), client.INT64, client.PLAIN, client.SNAPPY)
		initTimeSeries(ins, fmt.Sprintf("%s.mem_used", dbName), client.INT64, client.PLAIN, client.SNAPPY)
		initTimeSeries(ins, fmt.Sprintf("%s.mem_free", dbName), client.INT64, client.PLAIN, client.SNAPPY)
		initTimeSeries(ins, fmt.Sprintf("%s.mem_used_percent", dbName), client.DOUBLE, client.PLAIN, client.SNAPPY)
		for i := 0; i < len(data.CoreUsages); i++ {
			initTimeSeries(ins, fmt.Sprintf("%s.core_usages_%d", dbName, i), client.DOUBLE, client.PLAIN, client.SNAPPY)
		}
	}
	loggerv.GetLogger().Info("Insert into data", zap.String("path", dbName), zap.Any("data", data))
	if ins.InsertTabletByServerData(dbName, data) != nil {
		loggerv.Logger.Error("Insert data failed")
	}

}
func initTimeSeries(ins *iotdb.IoTDB, path string, dataType client.TSDataType, encoding client.TSEncoding, compressor client.TSCompressionType) {
	series := ins.CountTimeSeries(path)
	if series == 0 {
		loggerv.Logger.Info("time Series not exist", zap.Any("path:", path))
		ins.CreateTimeSeries(path, dataType, encoding, compressor)
	}
}

func handleGetHosts() interface{} {
	return monitor.Hosts.HostDeviceNames
}

// func handleLastCpuAndMem() (interface{}, error) {
// 	ins := iotdb.GetInstance()
// 	series, err := ins.QueryTimeSeries("select last  total_cpu_usage,mem_used_percent from root.vms.*")
// 	if err == nil {
// 		loggerv.Logger.Info("Read .", zap.Any("data list:", series))
// 		return series, nil
// 	} else {
// 		loggerv.Logger.Info("Can't read data .")
// 		return nil, err
// 	}
// }

func handleLastIndexes() (interface{}, error) {
	ins := iotdb.GetInstance()
	series, err := ins.QueryTimeSeries("select last  * from root.vms.*")
	if err == nil {
		loggerv.Logger.Info("Read .", zap.Any("data list:", series))
		return series, nil
	} else {
		loggerv.Logger.Info("Can't read data .")
		return nil, err
	}
}

func handleGetindexsByTimes(cmd cmd.CmdGetindexsByTimes) (interface{}, error) {
	proportion := cmd.GetProportionByKeepRecords()
	loggerv.Logger.Info("get proportion", zap.Float32("proportion", proportion))
	startTime := cmd.StartTime.Format("2006-01-02T15:04:05")
	endTime := cmd.EndTime.Format("2006-01-02T15:04:05")
	sql := fmt.Sprintf(`select 
		equal_size_bucket_agg_sample(total_cpu_usage, 'type'='avg','proportion'='%v') as total_cpu_usage,equal_size_bucket_agg_sample(mem_used_percent, 'type'='avg','proportion'='%v') as mem_used_percent
		from root.vms.*  WHERE time >= %v AND time <= %v align by device`, proportion, proportion, startTime, endTime)
	loggerv.Logger.Info("get sql", zap.String("sql", sql))
	ins := iotdb.GetInstance()
	series, err := ins.QueryTotalVmRecord(sql)
	if err == nil {
		loggerv.Logger.Info("handleGetindexsByTimes .", zap.Any("data list:", series))
		return series, nil
	} else {
		loggerv.Logger.Info("Can't read data .")
		return nil, err
	}
}
